import logging
from datetime import datetime

import requests

from config.config import MainConfig
from utils.logUtils import log_util

baseUrl = MainConfig.baseUrl

headers = {
    "Authorization": "JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxNCwidXNlcm5hbWUiOiJ6enEiLCJleHAiOjE3MTMwNjI1MjQsImVtYWlsIjoiIiwib3JnYW5pemF0aW9uX2FjY291bnQiOiI5OTk5OTk5OTkifQ.IVFcfSynPe6XoOqE__Bvgc_AA8FttGrTBJwS6ffb6s8"
}


def judge_response(response):
    if response.status_code != 200:
        log_util.log(f"请求失败：{response.status_code} {response.url}", level=logging.ERROR)
        log_util.tk_log(f"服务器请求失败!请检查网络是否通畅")
        exit(0)


def get_task():
    """
    获取任务
    :return: 任务列表
    """
    url = f"{baseUrl}/distribute_task/selenium/?today=true"
    res = requests.get(url, headers=headers)
    judge_response(res)

    task = res.json()["results"]
    task.sort(key=lambda x: datetime.fromisoformat(x["clock_time"]))
    return task


def update_token(pk, token):
    """
    更新token
    :param pk: 账号id
    :param token: 账号token
    """
    url = f"{baseUrl}/platform_account/{pk}/"
    res = requests.put(url, json={'token': token}, headers=headers)
    judge_response(res)


def get_platform_account():
    """
    获取账号
    :return: 账号列表
    """
    url = f"{baseUrl}/employee/platform_account/"
    res = requests.get(url, headers=headers)
    judge_response(res)
    return res.json()


def update_platform_account(pk, data):
    url = f"{baseUrl}/platform_account/{pk}/"
    res = requests.put(url, json=data, headers=headers)
    judge_response(res)


def update_distribution_task(pk, data):
    url = f"{baseUrl}/distribute_task/{pk}/"
    res = requests.put(url, json=data, headers=headers)
    judge_response(res)


def create_account_content(data):
    url = f"{baseUrl}/monitoring_data/"
    res = requests.post(url, json=data, headers=headers)
    judge_response(res)


def get_user_is_login():
    url = f"{baseUrl}/users/info/"
    res = requests.get(url, headers=headers)
    return res.status_code == 200
